package importExport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Vector;

import javax.media.j3d.QuadArray;
import javax.media.j3d.TriangleFanArray;
import javax.media.j3d.TriangleStripArray;
import javax.vecmath.Point3d;



public class OBJExporter {
	PrintStream p;
	Vector<Point3d> vertexCollection=new Vector<Point3d>();
	Vector<int[]>faceCollection;
	public OBJExporter (PrintStream p){
		this.p=p;
	}
	
	private  void writeVertex(double x, double y, double z){
		p.println("v "+x+" "+y+" "+z);
	}
	
	private  void writeVertex(Point3d v){
		writeVertex(v.x,v.y,v.z);
	}
	
	private void writeFace(int v1,int v2, int v3){
		p.println("f "+v1+" "+v2+" "+v3);
	}
	
	private void writeFace(int v1,int v2, int v3,int v4){
		p.println("f "+v1+" "+v2+" "+v3+" "+v4);
	}
	
	public void writeGeom(QuadArray geom){
		p.println("g");
		int n=geom.getVertexCount();
		Point3d[] coord=new Point3d[n];
		for (int i=0;i<coord.length;i++){
			coord[i]=new Point3d();
		}
		//geom.setCapability(QuadArray.ALLOW_COORDINATE_READ);
		geom.getCoordinates(0, coord);
		int startIndex=vertexCollection.size();
		for (int i=0;i<coord.length;i++){
			vertexCollection.add(coord[i]);
		}
		for (int i=0;i<coord.length;i+=4){
			int j=startIndex+i;
			writeFace(j+1,j+2,j+3,j+3);
		}
	}
	
	
	public void writeGeom(TriangleFanArray geom){
		p.println("g");
		int n=geom.getVertexCount();
		Point3d[] coord=new Point3d[n];
		for (int i=0;i<coord.length;i++){
			coord[i]=new Point3d();
		}
		//geom.setCapability(QuadArray.ALLOW_COORDINATE_READ);
		geom.getCoordinates(0, coord);
		int startIndex=vertexCollection.size();
		for (int i=0;i<coord.length;i++){
			vertexCollection.add(coord[i]);
		}
		for (int i=1;i<coord.length-1;i++){
			int j=startIndex+i;
			writeFace(startIndex+1,j+1,j+2);
		}
	}
	
	
	public void writeGeom(TriangleStripArray geom){
		p.println("g");
		//p.println("g "+(Math.random()*100));
		int n=geom.getVertexCount();
		Point3d[] coord=new Point3d[n];
		for (int i=0;i<coord.length;i++){
			coord[i]=new Point3d();
		}
		//geom.setCapability(QuadArray.ALLOW_COORDINATE_READ);
		geom.getCoordinates(0, coord);
		int startIndex=vertexCollection.size()+1;
		for (int i=0;i<coord.length;i++){
			vertexCollection.add(coord[i]);
		}
		for (int i=2;i<coord.length;i++){
			int j=startIndex+i;
			writeFace(j,j-1,j-2);
		}
	}
	
	
	FileOutputStream out;
	
	public   OBJExporter(File cFile){
		try {
			out = new FileOutputStream(cFile);
			 p = new PrintStream(out);
		} catch (Exception e) {
			System.err.println("error writing file");
		}
	}
	
	
	public void close(){
		for (int i=0;i<vertexCollection.size();i++){
			Point3d point=vertexCollection.get(i);
			this.writeVertex(point);
		}
		try {
			p.close();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

}
